package com.ruoyi.web.controller.jym;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.ImgUntil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.V2.inter.mapper.SalePartnerMapper;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.constant.GameJYMKeyUtil;
import com.ruoyi.system.outto.dto.JiaoYiMaoAttrUtil;
import com.ruoyi.web.controller.jym.domin.JYMPush;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.net.HttpCookie;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 推送管理池Controller
 * 
 * @author ruoyi
 * @date 2022-10-08
 */
@RestController
@RequestMapping("/jym/push")
public class JYMpushController extends BaseController
{
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    GoodsInfoMapper goodsInfoMapper;
    @Resource
    SalePartnerMapper salePartnerMapper;
    @Resource
    private SysDictDataMapper sysDictDataMapper;
    
    @PostMapping("/deleteqrrecord")
    public  String deleteqrrecord(String taskId,long saleId){

        SalePartner salePartner = salePartnerMapper.selectSalePartnerById(saleId);
        String data = "{\"taskId\":\""+taskId+"\"}";

        HttpResponse response = getToken();
        //获取到token
        HttpCookie m_h5_tk = response.getCookie("_m_h5_tk");
        String _m_h5_tk = m_h5_tk.getValue();
        HttpCookie m_h5_tk_enc = response.getCookie("_m_h5_tk_enc");
        String _m_h5_tk_enc = m_h5_tk_enc.getValue();
        String cookie = JiaoYiMaoAttrUtil.getCookie(_m_h5_tk, _m_h5_tk_enc, salePartner.getSaleKey());

        String jsv = "2.7.2";
        String appKey = "12574478";
        String token = _m_h5_tk.split("_")[0];
        String t = String.valueOf(System.currentTimeMillis());
        System.out.println(t);
        StringBuffer query = new StringBuffer();


        query.append(token).append("&").append(t).append("&").append(appKey).append("&").append(JSONObject.parseObject(data).toJSONString());

        String sign = DigestUtils.md5Hex(query.toString());
        HttpResponse rawResponse = HttpRequest.post("https://mtop.jiaoyimao.com/h5/mtop.jym.jymgoods.goods.autorecognizeproperty.deleteqrrecord/1.0/")
                .form("data", JSONObject.parseObject(data))
                .form("jsv", jsv)
                .form("appKey", appKey)
                .form("t", t)
                .form("sign", sign)
                .header("cookie", cookie)
                .execute();
        String body = rawResponse.body();
        return body;
    }

    @PostMapping("/publishGoods")
    public String publishGoods(@RequestBody JYMPush jymPush){
        GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto = goodsInfoMapper.selectGoodsInfoAndAttrValueById(jymPush.getGoodId());
        SalePartner salePartner = salePartnerMapper.selectSalePartnerById(jymPush.getSaleId());

        HttpResponse response = getToken();
        //获取到token
        HttpCookie m_h5_tk = response.getCookie("_m_h5_tk");
        String _m_h5_tk = m_h5_tk.getValue();
        HttpCookie m_h5_tk_enc = response.getCookie("_m_h5_tk_enc");
        String _m_h5_tk_enc = m_h5_tk_enc.getValue();
        String cookie = JiaoYiMaoAttrUtil.getCookie(_m_h5_tk, _m_h5_tk_enc, salePartner.getSaleKey());

        String jsv = "2.7.2";
        String token = _m_h5_tk.split("_")[0];
        String t = String.valueOf(System.currentTimeMillis());
        StringBuffer query = new StringBuffer();

        JSONObject jsonObject = JSONObject.parseObject(jymPush.getBody());
        String status = jsonObject.getString("status");
        if(status.equals("2")){
            //调发布
            String propertyValueResultList = jsonObject.getString("propertyValueResultList");
            String str = salePartner.getSaleKey();
            //封装参数
            String data = params(goodsInfoAndAttrValueDto,_m_h5_tk,cookie, salePartner,propertyValueResultList);
            System.out.println(data);
            String s = "12574478";
            query.append(token).append("&").append(t).append("&").append(s).append("&").append(data);
            String algSign = DigestUtils.md5Hex(query.toString());
            HttpResponse rawResponse1 = HttpRequest.post("https://mtop.jiaoyimao.com/h5/mtop.jym.jymsell.item.publish.pc.publishiteminpc/1.0/")
                    .form("data", data)
                    .form("jsv", jsv)
                    .form("appKey", s)
                    .form("t", t)
                    .form("sign", algSign)
                    .form("dataType", "json")
                    .form("valueType", "original")
                    .form("api", "mtop.jym.jymsell.item.publish.pc.publishItemInPc")
                    .form("v", "1.0")
                    .form("type", "originaljson")
                    .form("preventFallback", "true")
                    .header("authority", "mtop.jiaoyimao.com")
                    .header("accept", "application/json")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .header("jym-session-id", str)
                    .header("origin", "https://www.jiaoyimao.com")
                    .header("referer", "https://www.jiaoyimao.com/")
                    .header("jym-meta-h5", "{\"sid\":\"3031712045635546\",\"ssids\":\"3031712045635546\"," +
                            "\"ch\":\"10438\",\"plat\":\"JYM_IOS_TOUCH\",\"platform\":\"JYM_IOS_TOUCH\"," +
                            "\"terminal\":\"pc\"," +
                            "\"osCode\":\"other\",\"chCode\":\"h5\"}")
                    .header("cookie", cookie)
                    .execute();
            String body1 = rawResponse1.body();
            System.out.println(body1);
            try {
                String data1 = JSONObject.parseObject(body1).getString("data");
                String result2 = JSONObject.parseObject(data1).getString("result");
                String success = JSONObject.parseObject(result2).getString("success");
                if ("false".equals(success)) {
                } else {
                    String result1 = JSONObject.parseObject(data1).getString("result");
                    String goodsId = JSONObject.parseObject(result1).getString("goodsId");
                    ArtRec artRecreq = new ArtRec();
                    artRecreq.setConfig(salePartner.getId());
                    artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                    List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
                    if (artRecs.size() > 0) {
                        artRecs.get(0).setOutid(goodsId);
                        artRecMapper.updateArtRec(artRecs.get(0));
                    } else {
                        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                        artRecreq.setCreateId(goodsInfoAndAttrValueDto.getCreateId());
                        artRecreq.setType(LCConstant.interAdd);
                        artRecreq.setConfig(salePartner.getId());
                        artRecreq.setSaleCode(salePartner.getSaleName());
                        artRecreq.setOutid(goodsId);
                        artRecMapper.insertArtRec(artRecreq);
                    }
                }
                return body1;
            }catch (Exception e){
                return body1;
            }
        }else {
            throw new GlobalException("json数据为空");
        }
    }

    @PostMapping("/getqrrecognizeinfo")
    public String getqrrecognizeinfo(String taskId,long saleId,long goodId){
        SalePartner salePartner = salePartnerMapper.selectSalePartnerById(saleId);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("taskId",taskId);

        HttpResponse response = getToken();
        //获取到token
        HttpCookie m_h5_tk = response.getCookie("_m_h5_tk");
        String _m_h5_tk = m_h5_tk.getValue();
        HttpCookie m_h5_tk_enc = response.getCookie("_m_h5_tk_enc");
        String _m_h5_tk_enc = m_h5_tk_enc.getValue();
        String cookie = JiaoYiMaoAttrUtil.getCookie(_m_h5_tk, _m_h5_tk_enc, salePartner.getSaleKey());

        String jsv = "2.7.2";
        String appKey = "12574478";
        String token = _m_h5_tk.split("_")[0];
        String t = String.valueOf(System.currentTimeMillis());
        StringBuffer query = new StringBuffer();


        query.append(token).append("&").append(t).append("&").append(appKey).append("&").append(jsonObject1.toJSONString());

        String sign = DigestUtils.md5Hex(query.toString());
        HttpResponse rawResponse = HttpRequest.post("https://mtop.jiaoyimao.com/h5/mtop.jym.jymgoods.goods.autorecognizeproperty.getqrrecognizeinfo/1.0/")
                .form("data", jsonObject1)
                .form("jsv", jsv)
                .form("appKey", appKey)
                .form("t", t)
                .form("sign", sign)
                .header("cookie", cookie)
                .execute();
        String body = rawResponse.body();
        return body;
    }

    @PostMapping("/applyqrrecognize")
    public  String applyqrrecognize(long goodId,long saleId){
        SalePartner salePartner = salePartnerMapper.selectSalePartnerById(saleId);
        GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto = goodsInfoMapper.selectGoodsInfoAndAttrValueById(goodId);
        JSONObject jsonObject = new JSONObject();
        if(goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟")){
            String servers = "[{\"gameId\":1005654,\"grade\":31,\"id\":1517384142749498,\"isTop\":2,\"name\":\"峡谷之巅\"},{\"gameId\":1005654,\"grade\":30,\"id\":1500544100659844,\"isTop\":2,\"name\":\"男爵领域\"},{\"gameId\":1005654,\"grade\":29,\"id\":1500544100659842,\"isTop\":2,\"name\":\"教育网专区\"},{\"gameId\":1005654,\"grade\":28,\"id\":1500530737314623,\"isTop\":2,\"name\":\"钢铁烈阳\"},{\"gameId\":1005654,\"grade\":27,\"id\":1500530737313622,\"isTop\":2,\"name\":\"雷瑟守备\"},{\"gameId\":1005654,\"grade\":26,\"id\":1500530737313621,\"isTop\":2,\"name\":\"皮城警备\"},{\"gameId\":1005654,\"grade\":25,\"id\":1500530737313620,\"isTop\":2,\"name\":\"影流\"},{\"gameId\":1005654,\"grade\":24,\"id\":1500530737313618,\"isTop\":2,\"name\":\"水晶之痕\"},{\"gameId\":1005654,\"grade\":23,\"id\":1500530737313615,\"isTop\":2,\"name\":\"暗影岛\"},{\"gameId\":1005654,\"grade\":22,\"id\":1500530737313614,\"isTop\":2,\"name\":\"裁决之地\"},{\"gameId\":1005654,\"grade\":21,\"id\":1500530737313612,\"isTop\":2,\"name\":\"扭曲丛林\"},{\"gameId\":1005654,\"grade\":20,\"id\":1500530737312610,\"isTop\":2,\"name\":\"无畏先锋\"},{\"gameId\":1005654,\"grade\":19,\"id\":1500530737312608,\"isTop\":2,\"name\":\"德玛西亚\"},{\"gameId\":1005654,\"grade\":18,\"id\":1500530737312607,\"isTop\":2,\"name\":\"巨龙之巢\"},{\"gameId\":1005654,\"grade\":17,\"id\":1500530737312603,\"isTop\":2,\"name\":\"恕瑞玛\"},{\"gameId\":1005654,\"grade\":16,\"id\":1500530737312601,\"isTop\":2,\"name\":\"弗雷尔卓德\"},{\"gameId\":1005654,\"grade\":15,\"id\":1500450488530356,\"isTop\":2,\"name\":\"卡拉曼达\"},{\"gameId\":1005654,\"grade\":14,\"id\":1500450488530355,\"isTop\":2,\"name\":\"征服之海\"},{\"gameId\":1005654,\"grade\":13,\"id\":1500450488530354,\"isTop\":2,\"name\":\"守望之海\"},{\"gameId\":1005654,\"grade\":12,\"id\":1500450488530353,\"isTop\":2,\"name\":\"均衡教派\"},{\"gameId\":1005654,\"grade\":11,\"id\":1500450488530352,\"isTop\":2,\"name\":\"黑色玫瑰\"},{\"gameId\":1005654,\"grade\":10,\"id\":1500450488529351,\"isTop\":2,\"name\":\"巨神峰\"},{\"gameId\":1005654,\"grade\":9,\"id\":1500450488529349,\"isTop\":2,\"name\":\"战争学院\"},{\"gameId\":1005654,\"grade\":8,\"id\":1500450488529347,\"isTop\":2,\"name\":\"皮尔特沃夫\"},{\"gameId\":1005654,\"grade\":7,\"id\":1500450488529346,\"isTop\":2,\"name\":\"班德尔城\"},{\"gameId\":1005654,\"grade\":6,\"id\":1500450488529344,\"isTop\":2,\"name\":\"诺克萨斯\"},{\"gameId\":1005654,\"grade\":5,\"id\":1500450488529342,\"isTop\":2,\"name\":\"祖安\"},{\"gameId\":1005654,\"grade\":4,\"id\":1500450488529341,\"isTop\":2,\"name\":\"比尔吉沃特\"},{\"gameId\":1005654,\"grade\":3,\"id\":1500450488528338,\"isTop\":2,\"name\":\"艾欧尼亚\"}]\n";
            JSONArray jsonArray = JSONArray.parseArray(servers);
            String serverId = "";
            for(Object o : jsonArray){
                if(JSONObject.parseObject(o.toString()).getString("name").equals(goodsInfoAndAttrValueDto.getServerName())){
                    serverId = JSONObject.parseObject(o.toString()).getString("id");
                }
            }

            jsonObject.put("categoryId","1719886237225367");
            jsonObject.put("gameAccount",goodsInfoAndAttrValueDto.getAccountNumber());
            jsonObject.put("serverId",serverId);
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟(手游)")){
            String partition = goodsInfoAndAttrValueDto.getSystemName() + goodsInfoAndAttrValueDto.getCarrierName();
            String serverId = "";
            if (Objects.equals("安卓QQ", partition)) {
                serverId = "1719886462779126";
            } else if (Objects.equals("安卓微信", partition)) {
                throw new GlobalException("微信区不支持!!!");
            } else if (Objects.equals("苹果QQ", partition)) {
                serverId = "1719886587303694";
            } else if (Objects.equals("苹果微信", partition)) {
                throw new GlobalException("微信区不支持!!!");
            }
            jsonObject.put("categoryId",serverId);
            jsonObject.put("gameAccount",goodsInfoAndAttrValueDto.getAccountNumber());
            jsonObject.put("serverId","1633681463744104");
        }
        HttpResponse response = getToken();
        //获取到token
        HttpCookie m_h5_tk = response.getCookie("_m_h5_tk");
        String _m_h5_tk = m_h5_tk.getValue();
        HttpCookie m_h5_tk_enc = response.getCookie("_m_h5_tk_enc");
        String _m_h5_tk_enc = m_h5_tk_enc.getValue();
        String cookie = JiaoYiMaoAttrUtil.getCookie(_m_h5_tk, _m_h5_tk_enc, salePartner.getSaleKey());

        String jsv = "2.7.2";
        String appKey = "12574478";
        String token = _m_h5_tk.split("_")[0];
        String t = String.valueOf(System.currentTimeMillis());
        System.out.println(t);
        StringBuffer query = new StringBuffer();


        query.append(token).append("&").append(t).append("&").append(appKey).append("&").append(jsonObject.toJSONString());

        String sign = DigestUtils.md5Hex(query.toString());
        HttpResponse rawResponse = HttpRequest.post("https://mtop.jiaoyimao.com/h5/mtop.jym.jymgoods.goods.autorecognizeproperty.applyqrrecognize/1.0/")
                .form("data", jsonObject)
                .form("jsv", jsv)
                .form("appKey", appKey)
                .form("t", t)
                .form("sign", sign)
                .header("cookie", cookie)
                .execute();
        String body = rawResponse.body();
        String data = JSONObject.parseObject(body).getString("data");
        if(data.contains("result")){
            String result = JSONObject.parseObject(data).getString("result");
            if(!JSONObject.parseObject(result).getString("status").equals("2")) {
                String taskId = deleteqrrecord(JSONObject.parseObject(result).getString("taskId"), saleId);
                String applyqrrecognize = applyqrrecognize(goodId, saleId);
                return applyqrrecognize;
            }
            return body;
        }else {
            return data;
        }
    }


     HttpResponse getToken() {
        String t = String.valueOf(new Date().getTime());
        String token = "e2a7c26a6f259abbfbf16c92baa01906";
        String _m_h5_tk = token + "_" + t;
        //先请求一个cookie为空

        HttpResponse response = getRes(null, t, token, null);
        String body = response.body();
        return response;
    }


    public  HttpResponse getRes(String cookie, String t, String token, String data) {

        String baseUrl = "https://mtop.jiaoyimao.com/h5/mtop.com.jym.layout.hsf.goodslist.getgoodslist/1.0/";
        String jsv = "2.7.2";
        String s = "12574478";

        StringBuffer query = new StringBuffer();
        query.append(token).append("&").append(t).append("&").append(s).append("&").append(data);
        String algSign = DigestUtils.md5Hex(query.toString());
        HttpResponse response = HttpRequest.get(baseUrl)
                .form("jsv", jsv)
                .form("appKey", s)
                .form("t", t)
                .form("sign", algSign)
                .form("type", "originaljson")
                .form("v", "1.0")
                .form("valueType", "original")
                .form("dataType", "json")
                .form("api", "mtop.com.jym.layout.hsf.goodslist.getGoodsList")
                .form("preventFallback", "true")
                .form("data", data)
                .header("authority", "mtop.jiaoyimao.com")
                .header("accept", "application/json")
                .header("content-type", "application/x-www-form-urlencoded")
                .header("content-type", "application/x-www-form-urlencoded")
                .header("jym-meta-h5", "{\"sid\":\"5541701826074943\",\"ssids\":\"5541701826074943\"," +
                        "\"platform\":\"JYM_IOS_TOUCH\",\"plat\":\"JYM_IOS_TOUCH\",\"osCode\":\"ios\"," +
                        "\"chCode\":\"h5\"," +
                        "\"ch\":\"10438\",\"vername\":\"\"}")
                .header("cookie", cookie)
                .execute();
        return response;
    }


    private String params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String _m_h5_tk, String cookie,
                          SalePartner salePartner,String propertyValueResultList) {
        JSONObject dataJson = new JSONObject();
        dataJson.put("title", "商品标题将由系统生成");

        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        if(infoImgs.size()>20){
            infoImgs = infoImgs.subList(0,19);
        }
        String imgs = infoImgs.stream().map(i -> i.getImgUrl()).collect(Collectors.joining(","));
        Map<String, Object> imgMap = imgUpload(cookie, _m_h5_tk, imgs);

        dataJson.put("image", JSONObject.toJSONString(imgMap.get("images")));
        dataJson.put("imageIdListStr", imgMap.get("imageIdListStr"));

        //过滤关键词
        String des = guolvDes(goodsInfoAndAttrValueDto.getDes());
        des = des.length() > 100 ? des.substring(0, 100) : des;
        dataJson.put("description", "编号:"+goodsInfoAndAttrValueDto.getId()+des);
        dataJson.put("price", goodsInfoAndAttrValueDto.getPrice().toPlainString());
        dataJson.put("priceYuan", goodsInfoAndAttrValueDto.getPrice().toPlainString());
        dataJson.put("storage", "1");
        dataJson.put("_protocol", "true");
        dataJson.put("modelType", "pc");
        dataJson.put("goodsDefTravelContent", "{\"forceBargain\":true}");
        dataJson.put("addlService", "{\"supportBargain\":false}");
        dataJson.put("propertyRecognizeType", "2");

        JSONArray jsonArray4 = JSONArray.parseArray(propertyValueResultList);
        if (goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟")){
            dataJson.put("goodsDefTravelContent", "");
            //服务器
            dataJson.put("keyProperties","[{\"tags\":[{\"tagCode\":\"gameServer\"}],\"propertyName\":\"服务器\"}]");

            dataJson.put("description",goodsInfoAndAttrValueDto.getDes().substring(0,50));

            String gameId = "1005654";
            String clientId = "1472625225736942";
            String categoryId = "1719886237225367";

            String data1 = "{\"gameId\":\""+gameId+"\",\"clientId\":\""+clientId+"\",\"platformId\":\"5\",\"categoryId\":\""+categoryId+"\",\"isEdit\":false}";
            String attr = getAttr(data1,salePartner);
            String data = JSONObject.parseObject(attr).getString("data");
            String result = JSONObject.parseObject(data).getString("result");
            String categoryBaseInfo = JSONObject.parseObject(result).getString("categoryBaseInfo");
            String sellerAccountPropertiess = JSONObject.parseObject(result).getString("sellerAccountProperties");
            JSONArray jsonArray2 = JSONArray.parseArray(sellerAccountPropertiess);

            //账号信息
            Map<String,Object> sellerAccountProperties = new HashMap<>();
            List list = new ArrayList<>();
            for(Object o : jsonArray2){
                sellerAccountProperties = new HashMap<>();
                if(JSONObject.parseObject(o.toString()).getString("propertyName").equals("QQ帐号")) {
                    //"游戏帐号"
                    sellerAccountProperties.put("propertyId", JSONObject.parseObject(o.toString()).getString("propertyId"));
                    sellerAccountProperties.put("value", goodsInfoAndAttrValueDto.getAccountNumber().substring(0,goodsInfoAndAttrValueDto.getAccountNumber().length()-2)+ RandomUtil.randomNumbers(2));
                }else if(JSONObject.parseObject(o.toString()).getString("propertyName").equals("QQ密码")) {
                    //"游戏密码"
                    sellerAccountProperties.put("propertyId", JSONObject.parseObject(o.toString()).getString("propertyId"));
                    sellerAccountProperties.put("value", String.valueOf(System.currentTimeMillis()).substring(3));
                }else if(JSONObject.parseObject(o.toString()).getString("propertyName").equals("手机号码")){
                    // 手机号码
                    sellerAccountProperties.put("propertyId", JSONObject.parseObject(o.toString()).getString("propertyId"));
                    sellerAccountProperties.put("value",salePartner.getOther());
                }
                list.add(sellerAccountProperties);
            }
            dataJson.put("sellerAccountProperties",JSONObject.toJSONString(list));
            dataJson.put("categoryId","1719886237225367");
            Map<String,Object> gameProperty = new HashMap<>();
            gameProperty.put("gameId",JSONObject.parseObject(categoryBaseInfo).getString("newGameId"));
            gameProperty.put("platformId",JSONObject.parseObject(categoryBaseInfo).getString("platformId"));
            gameProperty.put("clientId","1472625225736942");
            gameProperty.put("categoryId","1719886237225367");
            String qufu = "[{\"gameId\":1005654,\"grade\":31,\"id\":1517384142749498,\"isTop\":2,\"name\":\"峡谷之巅\"},{\"gameId\":1005654,\"grade\":30,\"id\":1500544100659844,\"isTop\":2,\"name\":\"男爵领域\"},{\"gameId\":1005654,\"grade\":29,\"id\":1500544100659842,\"isTop\":2,\"name\":\"教育网专区\"},{\"gameId\":1005654,\"grade\":28,\"id\":1500530737314623,\"isTop\":2,\"name\":\"钢铁烈阳\"},{\"gameId\":1005654,\"grade\":27,\"id\":1500530737313622,\"isTop\":2,\"name\":\"雷瑟守备\"},{\"gameId\":1005654,\"grade\":26,\"id\":1500530737313621,\"isTop\":2,\"name\":\"皮城警备\"},{\"gameId\":1005654,\"grade\":25,\"id\":1500530737313620,\"isTop\":2,\"name\":\"影流\"},{\"gameId\":1005654,\"grade\":24,\"id\":1500530737313618,\"isTop\":2,\"name\":\"水晶之痕\"},{\"gameId\":1005654,\"grade\":23,\"id\":1500530737313615,\"isTop\":2,\"name\":\"暗影岛\"},{\"gameId\":1005654,\"grade\":22,\"id\":1500530737313614,\"isTop\":2,\"name\":\"裁决之地\"},{\"gameId\":1005654,\"grade\":21,\"id\":1500530737313612,\"isTop\":2,\"name\":\"扭曲丛林\"},{\"gameId\":1005654,\"grade\":20,\"id\":1500530737312610,\"isTop\":2,\"name\":\"无畏先锋\"},{\"gameId\":1005654,\"grade\":19,\"id\":1500530737312608,\"isTop\":2,\"name\":\"德玛西亚\"},{\"gameId\":1005654,\"grade\":18,\"id\":1500530737312607,\"isTop\":2,\"name\":\"巨龙之巢\"},{\"gameId\":1005654,\"grade\":17,\"id\":1500530737312603,\"isTop\":2,\"name\":\"恕瑞玛\"},{\"gameId\":1005654,\"grade\":16,\"id\":1500530737312601,\"isTop\":2,\"name\":\"弗雷尔卓德\"},{\"gameId\":1005654,\"grade\":15,\"id\":1500450488530356,\"isTop\":2,\"name\":\"卡拉曼达\"},{\"gameId\":1005654,\"grade\":14,\"id\":1500450488530355,\"isTop\":2,\"name\":\"征服之海\"},{\"gameId\":1005654,\"grade\":13,\"id\":1500450488530354,\"isTop\":2,\"name\":\"守望之海\"},{\"gameId\":1005654,\"grade\":12,\"id\":1500450488530353,\"isTop\":2,\"name\":\"均衡教派\"},{\"gameId\":1005654,\"grade\":11,\"id\":1500450488530352,\"isTop\":2,\"name\":\"黑色玫瑰\"},{\"gameId\":1005654,\"grade\":10,\"id\":1500450488529351,\"isTop\":2,\"name\":\"巨神峰\"},{\"gameId\":1005654,\"grade\":9,\"id\":1500450488529349,\"isTop\":2,\"name\":\"战争学院\"},{\"gameId\":1005654,\"grade\":8,\"id\":1500450488529347,\"isTop\":2,\"name\":\"皮尔特沃夫\"},{\"gameId\":1005654,\"grade\":7,\"id\":1500450488529346,\"isTop\":2,\"name\":\"班德尔城\"},{\"gameId\":1005654,\"grade\":6,\"id\":1500450488529344,\"isTop\":2,\"name\":\"诺克萨斯\"},{\"gameId\":1005654,\"grade\":5,\"id\":1500450488529342,\"isTop\":2,\"name\":\"祖安\"},{\"gameId\":1005654,\"grade\":4,\"id\":1500450488529341,\"isTop\":2,\"name\":\"比尔吉沃特\"},{\"gameId\":1005654,\"grade\":3,\"id\":1500450488528338,\"isTop\":2,\"name\":\"艾欧尼亚\"}]\n";
            JSONArray jsonArray = JSONArray.parseArray(qufu);
            for(Object o : jsonArray){
                if(JSONObject.parseObject(o.toString()).getString("name").equals(goodsInfoAndAttrValueDto.getServerName())){
                    gameProperty.put("serverId",JSONObject.parseObject(o.toString()).getString("id"));
                    break;
                }
            }
            dataJson.put("gameProperty", JSONObject.toJSONString(gameProperty));

            //属性
            Map<String,Object> extProperties = new HashMap<>();
//            String extPropertiess = JSONObject.parseObject(result).getString("extProperties");
//            JSONArray jsonArray3 = JSONArray.parseArray(extPropertiess);
            list = new ArrayList<>();
            for (Object p : jsonArray4) {
                String value = JSONObject.parseObject(p.toString()).getString("value");
                if(StringUtils.isNotEmpty(value)) {
                    extProperties = new HashMap<>();
                    extProperties.put("multiSubPropertyInfoList" , new ArrayList<>());
                    extProperties.put("propertyId" , JSONObject.parseObject(p.toString()).getString("propertyId"));
                    extProperties.put("value" , JSONObject.parseObject(p.toString()).getString("value"));
                    if (Objects.nonNull(extProperties.get("propertyId"))) {
                        list.add(extProperties);
                    }
                }
            }

            extProperties = new HashMap<>();
            extProperties.put("propertyId", "1719886248781528");
            extProperties.put("multiSubPropertyInfoList" , new ArrayList<>());
            extProperties.put("value", StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF23()) ? goodsInfoAndAttrValueDto.getF23() : "0");
            list.add(extProperties);
//
//            extProperties = new HashMap<>();
//            extProperties.put("propertyId", "1719886248120297");
//            extProperties.put("multiSubPropertyInfoList" , new ArrayList<>());
//            extProperties.put("value", "觅心萝莉 金克丝 是心动啊");
//            list.add(extProperties);

            extProperties = new HashMap<>();
            extProperties.put("propertyId", "1719886237277393");
            extProperties.put("multiSubPropertyInfoList" , new ArrayList<>());
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF1())) {
                GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF1()));
                if (gameAttribute1.getFieldName().equals("有修改人脸机会/实名是本人")) {
                    extProperties.put("value", "可二次实名");
                } else {
                    extProperties.put("value", "不可二次实名");
                }
            } else {
                extProperties.put("value", "不可二次实名");
            }
            list.add(extProperties);
            dataJson.put("extProperties", JSONObject.toJSONString(list));
        }

        if (goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟(手游)")){
            dataJson.put("goodsDefTravelContent", "");
            //服务器
            dataJson.put("keyProperties", "[{\"tags\":[{\"tagCode\":\"gameServer\"}],\"propertyName\":\"服务器\"}]");

            String gameId = "1011518";
            String clientId = "";
            String categoryId = "";

            String regional = goodsInfoAndAttrValueDto.getSystemName()+goodsInfoAndAttrValueDto.getCarrierName();
            if(regional.equals("安卓QQ")) {
                clientId = "1470047031091455";
                categoryId = "1719886462779126";
            }else if(regional.equals("安卓微信")){
                clientId = "1470047033047733";
                categoryId = "1652861430355356";
            }else if(regional.equals("苹果QQ")){
                clientId = "1470047031280559";
                categoryId = "1719886587303694";
            }else {
                clientId = "1499667551454656";
                categoryId = "1652861525432266";
            }

            String data1 = "{\"gameId\":\""+gameId+"\",\"clientId\":\""+clientId+"\",\"platformId\":\"3\",\"categoryId\":\""+categoryId+"\",\"isEdit\":false}";
            System.out.println(data1);

            String attr = getAttr(data1,salePartner);
            String data = JSONObject.parseObject(attr).getString("data");
            String result = JSONObject.parseObject(data).getString("result");
            String categoryBaseInfo = JSONObject.parseObject(result).getString("categoryBaseInfo");
            String sellerAccountPropertiess = JSONObject.parseObject(result).getString("sellerAccountProperties");
            JSONArray jsonArray2 = JSONArray.parseArray(sellerAccountPropertiess);

            //账号信息
            Map<String,Object> sellerAccountProperties = new HashMap<>();
            List list = new ArrayList<>();
            for(Object o : jsonArray2){
                sellerAccountProperties = new HashMap<>();
                if(JSONObject.parseObject(o.toString()).getString("propertyName").equals("QQ帐号")) {
                    //"游戏帐号"
                    sellerAccountProperties.put("propertyId", JSONObject.parseObject(o.toString()).getString("propertyId"));
                    sellerAccountProperties.put("value", goodsInfoAndAttrValueDto.getAccountNumber().substring(0,goodsInfoAndAttrValueDto.getAccountNumber().length()-2)+ RandomUtil.randomNumbers(2));
                }else if(JSONObject.parseObject(o.toString()).getString("propertyName").equals("QQ密码")) {
                    //"游戏密码"
                    sellerAccountProperties.put("propertyId", JSONObject.parseObject(o.toString()).getString("propertyId"));
                    sellerAccountProperties.put("value", String.valueOf(System.currentTimeMillis()).substring(3));
                }else if(JSONObject.parseObject(o.toString()).getString("propertyName").equals("手机号码")){
                    // 手机号码
                    sellerAccountProperties.put("propertyId", JSONObject.parseObject(o.toString()).getString("propertyId"));
                    sellerAccountProperties.put("value",salePartner.getOther());
                }
                list.add(sellerAccountProperties);
            }
            dataJson.put("sellerAccountProperties",JSONObject.toJSONString(list));
            dataJson.put("categoryId",categoryId);
            Map<String,Object> gameProperty = new HashMap<>();
            gameProperty.put("gameId",JSONObject.parseObject(categoryBaseInfo).getString("newGameId"));
            gameProperty.put("platformId",JSONObject.parseObject(categoryBaseInfo).getString("platformId"));
            gameProperty.put("clientId",clientId);
            gameProperty.put("categoryId",categoryId);
            gameProperty.put("serverId","1633681463744104");
            dataJson.put("gameProperty", JSONObject.toJSONString(gameProperty));

            //属性
            Map<String,Object> extProperties = new HashMap<>();
            list = new ArrayList<>();
            for (Object p : jsonArray4) {
                String value = JSONObject.parseObject(p.toString()).getString("value");
                if(StringUtils.isNotEmpty(value)) {
                    extProperties = new HashMap<>();
                    extProperties.put("multiSubPropertyInfoList" , new ArrayList<>());
                    extProperties.put("propertyId" , JSONObject.parseObject(p.toString()).getString("propertyId"));
                    extProperties.put("value" , JSONObject.parseObject(p.toString()).getString("value"));
                    if (Objects.nonNull(extProperties.get("propertyId"))) {
                        list.add(extProperties);
                    }
                }
            }
            extProperties = new HashMap<>();
            extProperties.put("propertyId", "1719886587395707");
            extProperties.put("multiSubPropertyInfoList" , new ArrayList<>());
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF4())) {
                GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF4()));
                if (gameAttribute1.getFieldName().equals("可二次实名")) {
                    extProperties.put("value", "可二次实名");
                } else {
                    extProperties.put("value", "不可二次实名");
                }
            } else {
                extProperties.put("value", "不可二次实名");
            }
            list.add(extProperties);
            dataJson.put("extProperties", JSONObject.toJSONString(list));
        }

        return dataJson.toJSONString();
    }

    Map<String, Object> imgUpload(String cookie, String _m_h5_tk, String imgUrls) {
        String imageIdListStr = new String();
        List<Map<String, Object>> images = new ArrayList<>();
        Map<String, Object> imgMap = new HashMap<>();

        String jsv = "2.7.2";
        String appKey = "12574478";

        String token = _m_h5_tk.split("_")[0];
        String t = String.valueOf(new Date().getTime());

        //文件名称
        String[] imgs = imgUrls.split(",");
        List<String> list = Arrays.asList(imgs);
//        if (list.size() > 3) {
//            list = list.subList(0, 3);
//        }
        for (String img : list) {
            StringBuffer query = new StringBuffer();
            JSONObject data = new JSONObject();
            data.put("bizId", "1");
            String fieldName = img.substring(img.lastIndexOf("/") + 1);
            data.put("fileName", fieldName);

//        String data = "{\"bizId\":\"1\",\"fileName\":\"2c97e7c98e5f3329018e65763ab50c6b.jpg\"}";

            //获取交易猫图片上传 密钥
            String baseUrl = "https://mtop.jiaoyimao.com/h5/mtop.jym.fileserver.applyfileupload/1.0/";
            query.append(token).append("&").append(t).append("&").append(appKey).append("&").append(data);
            String algSign = DigestUtils.md5Hex(query.toString());
            Map<String, Object> params = new HashMap<>();
            Map<String, Object> header = new HashMap<>();
            header.put("Cookie", cookie);
            params.put("data", data.toJSONString());
            params.put("appKey", appKey);
            params.put("t", t);
            params.put("sign", algSign);
            String s = HttpUtils.doPostForm(baseUrl, params, header);
            JSONObject jsonObject = JSONObject.parseObject(s);
            JSONObject data1 = jsonObject.getJSONObject("data");
            JSONObject result = data1.getJSONObject("result");
            JSONObject credentials = result.getJSONObject("credentials");
            String securityToken = credentials.getString("securityToken");
            String accessKeyId = credentials.getString("accessKeyId");
            String accessKeySecret = credentials.getString("accessKeySecret");

            String env = result.getString("pathList");
            List<String> stringList = JSONArray.parseArray(env, String.class);
            String path = stringList.get(0);

            URL url = null;
            byte[] bytes = {};
            try {
                url = new URL(img);
                BufferedImage bufferedImage = ImageIO.read(url.openStream());
                bytes = ImgUntil.bufferedImageToByteArray(bufferedImage);
                //如果是多图片，这里要循环上传图片，最好不要超过五张
                uoload(accessKeyId, accessKeySecret, securityToken, bytes, path);
                //验证图片
                //获取resultId，如果是多张图片 循环往 goodsImageDTOListStr 添加
                List<JSONObject> goodsImageDTOListStr = new ArrayList<>();
                JSONObject goodsImgeDto = new JSONObject();
                goodsImgeDto.put("originImage", "/" + path);
                goodsImgeDto.put("wapThumbnail", "/" + path);
                goodsImgeDto.put("pcThumbnail", "/" + path);
                goodsImgeDto.put("auditImage", "/" + path);
                goodsImageDTOListStr.add(goodsImgeDto);
                JSONObject goodsImageDTOParams = new JSONObject();
                goodsImageDTOParams.put("goodsImageDTOListStr", goodsImageDTOListStr.toString());
                String imgeResultId = getImgeResultId(goodsImageDTOParams.toString(), cookie, _m_h5_tk);


                //add图片上传参数
                //解析imgeResultId
                JSONObject jsonObject1 = JSONObject.parseObject(imgeResultId);
                JSONObject resdata = jsonObject1.getJSONObject("data");
                String result1 = resdata.getString("result");
                List<String> stringList1 = JSONObject.parseArray(result1, String.class);
                imageIdListStr += "," + StringUtils.join(stringList1, ",");
                //https://static-cdn.jiaoyimao.com/jym-oss/resource/item/1685196620085637/20240327
                // /7773173425da4ceea74709ea4092a667.jpg
                //童谣如果是多张图片 这也也是循环往images添加
                String baseDomain = "https://static-cdn.jiaoyimao.com/";
                JSONObject image = new JSONObject();
                image.put("url", baseDomain + path);
                image.put("onlinePath", "/" + path);
                images.add(image);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        imgMap.put("images", images);
        imgMap.put("imageIdListStr", imageIdListStr.substring(1));
        return imgMap;
    }


    static String getImgeResultId(String data, String cookie, String _m_h5_tk) {
        String baseUrl = "https://mtop.jiaoyimao.com/h5/mtop.jym.jymgoods.goods.publish.addimagerecordlistformtop/1.0/";

        String jsv = "2.7.2";
        String s = "12574478";

        String token = _m_h5_tk.split("_")[0];
        String t = String.valueOf(new Date().getTime());

        StringBuffer query = new StringBuffer();

        //撤回的时候传入商品ID   下架账号之后 都要先调一下撤回
        query.append(token).append("&").append(t).append("&").append(s).append("&").append(data);
        String algSign = DigestUtils.md5Hex(query.toString());
        HttpResponse rawResponse = HttpRequest.post(baseUrl)
                .form("data", data)
                .form("jsv", jsv)
                .form("appKey", s)
                .form("t", t)
                .form("sign", algSign)
                .form("dataType", "json")
                .form("valueType", "original")
                .form("api", "top.jym.jymgoods.goods.publish.addImageRecordListForMtop")
                .form("v", "1.0")
                .form("type", "originaljson")
                .form("preventFallback", "true")
                .header("authority", "mtop.jiaoyimao.com")
                .header("accept", "application/json")
                .header("content-type", "application/x-www-form-urlencoded")
                .header("jym-meta-h5", "{\"sid\":\"4461709102075386\",\"ssids\":\"4461709102075386\"," +
                        "\"ch\":\"10438\",\"plat\":\"JYM_IOS_TOUCH\",\"platform\":\"JYM_IOS_TOUCH\"," +
                        "\"terminal\":\"ios\"," +
                        "\"osCode\":\"ios\",\"chCode\":\"h5\"}")
                .header("cookie", cookie)
                .execute();
        String body = rawResponse.body();
        return body;
    }
    private String guolvDes(String des) {
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("jym_check");
        sysDictData.setStatus(Constants.STR_0);
        List<SysDictData> sysDictDataList = sysDictDataMapper.selectDictDataList(sysDictData);
        for (SysDictData dictData : sysDictDataList) {
            String value = dictData.getDictValue();
            if (des.contains(value)) {
                des = des.replace(value, "");
            }
        }
        return des;
    }

    String getAttr(String data,SalePartner salePartner){
        HttpResponse response = getToken();
        //获取到token
        HttpCookie m_h5_tk = response.getCookie("_m_h5_tk");
        String _m_h5_tk = m_h5_tk.getValue();
        HttpCookie m_h5_tk_enc = response.getCookie("_m_h5_tk_enc");
        String _m_h5_tk_enc = m_h5_tk_enc.getValue();
        String cookie = JiaoYiMaoAttrUtil.getCookie(_m_h5_tk, _m_h5_tk_enc, salePartner.getSaleKey());

        String jsv = "2.7.2";
        String appKey = "12574478";
        String token = _m_h5_tk.split("_")[0];
        String t = String.valueOf(new Date().getTime());
        StringBuffer query = new StringBuffer();


        query.append(token).append("&").append(t).append("&").append(appKey).append("&").append(JSONObject.parseObject(data).toJSONString());

        String sign = DigestUtils.md5Hex(query.toString());
        HttpResponse rawResponse = HttpRequest.post("https://mtop.jiaoyimao.com/h5/mtop.jym.jymgoods.goods.core.getgoodsdefforpc/1.0/")
                .form("data", JSONObject.parseObject(data))
                .form("jsv", jsv)
                .form("appKey", appKey)
                .form("t", t)
                .form("sign", sign)
//                .form("dataType", "json")
//                .form("valueType", "original")
//                .form("api", "mtop.jym.jymgoods.goods.autoRecognizeProperty.recognizeProperty")
//                .form("v", "1.0")
//                .form("type", "originaljson")
//                .form("preventFallback", "true")
//                .header("authority", "mtop.jiaoyimao.com")
//                .header("accept", "application/json")
//                .header("content-type", "application/x-www-form-urlencoded")
//                .header("jym-session-id", str)
//                .header("sec-ch-ua-platform", "Windows")
//                .header("origin", "https://www.jiaoyimao.com")
//                .header("sec-fetch-site", "same-site")
//                .header("sec-fetch-mode", "cors")
//                .header("sec-fetch-dest", "empty")
//                .header("referer", "https://www.jiaoyimao.com/")
                .header("cookie", cookie)
                .execute();
        String body = rawResponse.body();
        return body;
    }

    public static void uoload(String accessKeyId, String accessKeySecret, String securityToken, byte[] content,
                              String objectName) throws Exception {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-zhangjiakou.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret,
                securityToken);
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "jym-static";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName,
                    new ByteArrayInputStream(content));

            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);


        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }



    private List<GameAttribute> getGameAttributs(String ids) {
        List<GameAttribute> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(ids)) {
            list = gameAttributeMapper.selectGameAttributeListByIds((Long[]) ConvertUtils.convert(ids.split(","),
                    Long.class));
        }
        return list;
    }

    private String reIds(String allIds, String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            if (StringUtils.isNotEmpty(allIds)) {
                allIds = allIds + "," + ids;
            } else {
                allIds = ids;
            }
        }
        return allIds;
    }
}
